package com.magicalcoder.pigeon.client;


import com.magicalcoder.pigeon.common.message.PigeonResponse;

import java.util.concurrent.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by hzhedongyu on 2017/5/27.
 */
public class ClientFuture implements Future<PigeonResponse> {

    private ReentrantLock lock = new ReentrantLock();
    private PigeonResponse object;
    private CountDownLatch countDownLatch = new CountDownLatch(1);
    private volatile boolean done = false;

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        return false;
    }

    @Override
    public boolean isCancelled() {
        return false;
    }

    @Override
    public boolean isDone() {
        return done;
    }

    @Override
    public PigeonResponse get() throws InterruptedException, ExecutionException {
        lock.lock();
        try {
            countDownLatch.await();
            return object;
        }finally {
            lock.unlock();
        }
    }

    @Override
    public PigeonResponse get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        lock.tryLock();
        try {
            countDownLatch.await(timeout,unit);
            return object;
        }finally {
            lock.unlock();
        }
    }
    //任务完成

    public void finish(PigeonResponse object){
        this.object = object;
        countDownLatch.countDown();//使await不再等待
    }
}
